package com.wy.cms.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.wy.cms.util.ResourcesUtil;
import com.wy.common.exception.BizException;
import com.wy.constant.CookieConst;
import com.wy.protocol.ERRORCODE;
import com.wy.util.CookieUtil;
import com.wy.util.EncryptUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class ResourcesInterceptor implements HandlerInterceptor {

	public ResourcesInterceptor() { }

	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		String url = request.getServletPath();

		String value = CookieUtil.getCookieValue(request.getCookies(), CookieConst.WY_CMS_COOKIE_NAME);
		if(!StringUtils.isEmpty(value)){
			ResourcesUtil resourcesUtil = new ResourcesUtil();
			Long roleId = JSON.parseObject(EncryptUtil.decode(value)).getLong("roleId");
			if(!resourcesUtil.getResourceUrl(roleId).containsKey(url)) {
				throw new BizException(ERRORCODE.AUTHENTICATION_FAIL.getCode(), "没有权限");
//				response.setContentType(CodeConst.TEXT_HTML);
//				response.setCharacterEncoding(CodeConst.UTF_8);
//				PrintWriter out = null;
//				try{
//					out = response.getWriter();
//					out.println("没有权限!");
//				} catch (Exception e){
//					throw e;
//				} finally{
//					if(null!=out){
//						out.flush();
//						out.close();
//					}
//				}
//				request.getRequestDispatcher("/index.do").forward(request, response);
			}
			String requestType = request.getHeader("X-Requested-With");
			if(StringUtils.isEmpty(requestType)){
				request.setAttribute("privilegeId", resourcesUtil.getResourceUrl(roleId).get(url));
			}
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
		
	}

	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) throws Exception {
		
	}

}
